#include "uv_timer.h"

using namespace uvpp;

UVTimer::UVTimer(EventLoop* loop, uint64_t timeout, uint64_t repeat, TimeoutCallback callback)
	:_started(false),
	_timeout(timeout),
	_repeat(repeat),
	_onTimeoutCallback(callback)
{
	_timer.data = static_cast<void*>(this);
	::uv_timer_init(loop->raw(), &_timer);
}

UVTimer::~UVTimer()
{

}

void UVTimer::start()
{
	if (!_started)
	{
		::uv_timer_start(&_timer, [](uv_timer_t* handle)
		{
			auto timer = static_cast<UVTimer*>(handle->data);
			timer->onTimeout();
		}, _timeout, _repeat);
		_started = true;
	}
}

void UVTimer::stop(TimerStopComplete callback)
{
	_onStopCompleteCallback = callback;
	if (::uv_is_active((uv_handle_t*)&_timer))
	{
		::uv_timer_stop(&_timer);
	}

	if (::uv_is_closing((uv_handle_t*)&_timer) == 0)
	{
		::uv_close((uv_handle_t*)&_timer, 
			[](uv_handle_t* handle)
			{
				auto timer = static_cast<UVTimer*>(handle->data);
				timer->onStopComplete();
			});
	}
	else
	{
		onStopComplete();
	}
}

void UVTimer::setRepeat(uint64_t ms)
{
	_repeat = ms;
	::uv_timer_set_repeat(&_timer, ms);
}

void UVTimer::onTimeout()
{
	if (_onTimeoutCallback)
	{
		_onTimeoutCallback(this);
	}
}

void UVTimer::onStopComplete()
{
	if (_onStopCompleteCallback)
	{
		_onStopCompleteCallback(this);
	}
}
